/**
 * 
 */
package com.wubo.sec.web.action;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.wubo.common.util.CollectionUtils;
import com.wubo.common.util.StringUtils;
import com.wubo.sec.SecurityManager;
import com.wubo.sec.core.RoleData;
import com.wubo.sec.filter.RoleBeforeFilter;
import com.wubo.sec.model.Role;
import com.wubo.sec.service.IRoleService;

import flexjson.JSONSerializer;

/**
 * @author WuBo
 * @CreateDate 2010-8-6
 * @version 1.0.01
 */
@Controller
public class RoleMgtAction extends BaseSecAction {
	
	private List<Role> roles;
	private Role role;
	@Autowired
	private IRoleService roleService;
	
	private String roleName;
	
	private String orderby;
	
	private String locked;

	public String getLocked() {
		return locked;
	}

	public void setLocked(String locked) {
		this.locked = locked;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getOrderby() {
		return orderby;
	}

	public void setOrderby(String orderby) {
		this.orderby = orderby;
	}

	public IRoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	public String list(){
		String where = "where 1=1";
		if(StringUtils.hasText(roleName) ){
			where = " where r.roleName like '%"+roleName+"%' ";
		}
		if(!StringUtils.isEmpty(locked)){
			if(!(locked.trim().equals("2"))){
				where += " and locked = "+locked;
			}
		}
		if(StringUtils.isEmpty(orderby) ){
			orderby = "order by roleName";
		}
		where += new RoleBeforeFilter().sift();
		
		total = roleService.getTotal(where);
		
		where += orderby;
		
		roles = roleService.getSplitPage(start, limit, where);
		//角色实现类可能有多个，调用此方法的用户并不一定具有Role属性，这里不再加入
		/*Set<Role> userRoles = SecurityManager.getCurrentUser().getRoles();
		
		if(userRoles != null){
			roles.addAll(userRoles);
		}
		roles = CollectionUtils.uniqueList(roles);
		*/
		super.setUserAttributesToRequest();
		
		return SUCCESS;
	}
	
	/**
	 * 为分配角色或角色关联显示服务
	 * @return
	 */
	public String listForAssign(){
		String where = "where 1=1";
		//过滤roleName
		if(StringUtils.hasText(roleName)){
			where = "where r.roleName like '%"+roleName+"%'";
		}
		if(SecurityManager.isAdmin()){
			roles = roleService.find(where, null);
		}else{
			roles = roleService.findRunAs(where+new RoleBeforeFilter().sift(), null);
			
			Set<? extends RoleData> userRoles = SecurityManager.getCurrentUser().getRoles();
			
			if(userRoles != null){
				Set<Role> tempRoles = new LinkedHashSet<Role>(userRoles.size());
				for(Iterator<? extends RoleData> ite=userRoles.iterator(); ite.hasNext();){
					RoleData roleData = ite.next();
					if( roleData instanceof Role){
						//过滤roleName
						if(StringUtils.hasText(roleName)){
							if(roleData.getRoleName().indexOf(roleName) == -1){
								continue;
							}
						}
						tempRoles.add((Role) roleData);
					}
				}
				roles.addAll(tempRoles);
			}
			roles = CollectionUtils.uniqueList(roles);
		}
		String result = ServletActionContext.getRequest().getParameter("result");
		if(StringUtils.hasText(result)){
			return result;
		}
		return "checkbox";
	}

	private String q; //用于AutoComplete
	public String getQ() {
		return q;
	}
	public void setQ(String q) {
		this.q = q;
	}
	public void autoComplete() {
		try{
			List<String> names = roleService.listName(q);
			json(new JSONSerializer().serialize(names));
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
	}
	
	private String id;

	public String del(){
		roleService.delete(roleService.get(id));
		flag = true;
		
		list();
		
		return SUCCESS;
	}
	
	public String add(){
		try{
			role.setOwner(SecurityManager.getCurrentUser().getUsername());
			roleService.create(role);
			flag = true;
			
			list();
			
			jsonSuccess(null);
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}
	
	public String edit(){
		try{
			roleService.update(role);
			
			jsonSuccess(null);
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
}
